package exercise16;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Calculator extends JFrame implements ActionListener{
	/*16-4*/
	
	private double result;
	
	private JTextField jtfN1 = new JTextField();
	private JTextField jtfN2 = new JTextField();
	private JTextField jtfResult = new JTextField();
	
	private JButton jbtAdd = new JButton("Add");
	private JButton jbtSubtract = new JButton("Subtract");
	private JButton jbtMultiply = new JButton("Multiply");
	private JButton jbtDivide = new JButton("Divide");
	
	
	public Calculator(){
		
//		JPanel p1 = new JPanel(new FlowLayout(FlowLayout.LEFT, 2, 2));
		JPanel p1 = new JPanel(new GridLayout(1, 6, 1, 1));
		p1.add(new Label("Number 1"));
		p1.add(jtfN1);
		p1.add(new Label("Number 2"));
		p1.add(jtfN2);
		p1.add(new Label("Result"));
		p1.add(jtfResult);
		
		JPanel p2 = new JPanel(new FlowLayout());
		p2.add(jbtAdd);
		p2.add(jbtSubtract);
		p2.add(jbtMultiply);
		p2.add(jbtDivide);
		
		add(p1, BorderLayout.CENTER);
		add(p2, BorderLayout.SOUTH);
		
		jbtAdd.addActionListener(this);
		jbtSubtract.addActionListener(this);
		jbtMultiply.addActionListener(this);
		jbtDivide.addActionListener(this);

		
	}
	
	public void actionPerformed(ActionEvent e){
		double n1 = Double.parseDouble(jtfN1.getText());
		double n2 = Double.parseDouble(jtfN2.getText());
		
		if (e.getSource() == jbtAdd) {
			result = n1 + n2;
		}
		else if (e.getSource() == jbtSubtract) {
			result = n1 - n2;
		}
		else if (e.getSource() == jbtMultiply) {
			result = n1 * n2;
		}
		else if (e.getSource() == jbtDivide) {
			if (n2 == 0.0) {
				jtfResult.setText("Divisor cannot be zero");
				return;
			}
			else
				result = n1 / n2;
		}
		
		jtfResult.setText(String.format("%.2f",result));
	}
	

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		JFrame frame = new Calculator();
		frame.setTitle("Calculator");
		frame.setLocationRelativeTo(null);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.pack();
		frame.setVisible(true);
		
	}

}
